import java.util.PriorityQueue;

//创建一个类 表示一个任务
//指定优先级
class MyTimerTask2 implements Comparable<MyTimerTask2> {
    private Runnable runnable;
    private long time;

    public MyTimerTask2(Runnable runnable,long delay) {
        this.runnable = runnable;
        this.time = delay + System.currentTimeMillis();
    }

    public void run() {
        runnable.run();
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimerTask2 o) {
        return (int) (this.time - o.getTime());
    }
}

class MyTimer2 {
    //引入数据结构来保存多个任务
    PriorityQueue<MyTimerTask2> taskQueue = new PriorityQueue<>();
    Object locker = new Object();
    //引入扫描线程
    public MyTimer2() {
        Thread t = new Thread(() -> {
            synchronized (locker) {
                try {
                    while (true) {
                        if (taskQueue.size() == 0) {
                            locker.wait();
                        }
                        //队列不为空 取出元素判断是否可以执行
                        MyTimerTask2 task = taskQueue.peek();
                        long curtime = System.currentTimeMillis();
                        if(curtime >= task.getTime()) {
                            task.run();
                            taskQueue.poll();
                        } else {
                            locker.wait(task.getTime() - curtime);
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t.start();
    }

    //入队列 要加锁
    public void schedule(Runnable runnable,long delay) {
        synchronized(locker) {
            MyTimerTask2 task = new MyTimerTask2(runnable,delay);
            taskQueue.offer(task);
            locker.notify();
        }
    }
}


public class Demo_MyTimer {
    public static void main(String[] args) {
        MyTimer2 timer = new MyTimer2();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("run1 1000");
            }
        },1000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("run2 2000");
            }
        },2000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("run3 3000");
            }
        },3000);
    }
}
